﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Common.Text;
using SnippetBox.Core.Common.XSS;
using SnippetBox.Core.Data.Models;
using SnippetBox.Core.Data.Service;
using SnippetBox.Core.Infrastructure;
using SnippetBox.Core.Infrastructure.Security;
using SnippetBox.Web.Areas.Manage.Models;
using SnippetBox.Web.Models;

namespace SnippetBox.Web.Areas.Manage.Controllers {
    [Authorize(Roles = Roles.MEMBER), AllowedToCreateSnippet]
    public class SnippetsController : Controller {
        readonly SnippetService _snippetService = new SnippetService();

        public ActionResult Index(int? page, string query) {
            // Users of Member role can only edit their own content
            if (User.IsInRole(Roles.EDITOR)) {
                if (query.IsNullOrEmpty())
                    ViewData.Model = _snippetService.GetAllPaged(page);
                else
                    ViewData.Model = _snippetService.Search(query, page);
            }
            else {
                if (query.IsNullOrEmpty())
                    ViewData.Model = _snippetService.GetAllPagedByUser(page, User as User);
                else
                    ViewData.Model = _snippetService.SearchFromUser(query, page, User as User);
            }

            return View();
        }

        public ActionResult Create(int? categoryId) {
            var model = new SnippetModel();
            
            if (categoryId.HasValue)
                model.CategoryId = categoryId;

            return View(model);
        }

        [HttpPost]
        public ActionResult Create(SnippetModel snippetModel) {
            if (!ModelState.IsValid)
                return View(snippetModel);

            var userService = new UserService();
            var categoryService = new CategoryService();

            var snippet = new Snippet();
            snippet.BodyRaw = snippetModel.Snippet.BodyRaw;
            snippet.Body = new Markdown().Transform(snippetModel.Snippet.BodyRaw).ToSafeHtml();
            snippet.DateCreated = DateTime.Now;
            snippet.DateEdited = DateTime.Now;
            snippet.Title = snippetModel.Snippet.Title;
            snippet.Slug = snippetModel.Snippet.Title.Slugify();
            snippet.Author = userService.GetByUsername(User.Identity.Name);
            snippet.Category = categoryService.GetById(snippetModel.CategoryId.Value);

            _snippetService.Create(snippet);
            _snippetService.Save();

            TempData["Message"] = "The snippet has been created. <a href=\"{0}\">View the snippet.</a>".FormatWith(snippet.Link);
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id) {
            var snippet = _snippetService.GetById(id);

            if (snippet == null)
                return View("NotFound", new NotFoundModel());

            if (!snippet.CanEdit(User as User))
                return View("AccessDenied");

            var model = new SnippetModel(snippet);

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, SnippetModel snippetModel) {
            if (!ModelState.IsValid)
                return View(snippetModel);

            var categoryService = new CategoryService();
            var snippet = _snippetService.GetById(id);

            if (snippet == null)
                return View("NotFound", new NotFoundModel());

            if (!snippet.CanEdit(User as User))
                return View("AccessDenied");

            snippet.BodyRaw = snippetModel.Snippet.BodyRaw;
            snippet.Body = new Markdown().Transform(snippetModel.Snippet.BodyRaw).ToSafeHtml();
            snippet.DateEdited = DateTime.Now;
            snippet.Title = snippetModel.Snippet.Title;
            snippet.Slug = snippetModel.Snippet.Title.Slugify();
            snippet.Category = categoryService.GetById(snippetModel.CategoryId.Value);

            _snippetService.Save();

            TempData["Message"] = "The snippet has been updated. <a href=\"{0}\">View the snippet.</a>".FormatWith(snippet.Link);
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id) {
            var snippet = _snippetService.GetById(id);

            if (snippet == null)
                return View("NotFound", new NotFoundModel());

            if (!snippet.CanEdit(User as User))
                return View("AccessDenied");

            return View(snippet);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeletePost(int id) {
            var snippet = _snippetService.GetById(id);

            if (snippet == null)
                return View("NotFound", new NotFoundModel());

            if (!snippet.CanEdit(User as User))
                return View("AccessDenied");

            snippet.IsDeleted = !snippet.IsDeleted;
            _snippetService.Save();

            if (Request.IsAjaxRequest())
                return Json(new { subject = snippet.Title, predicate = "was deleted" });

            return RedirectToAction("Index");
        }

    }
}
